文章目录
  1. 1. 题目
  2. 2. 思路
  3. 3. 代码

本系列代码见我的Leetcode仓库

题目

Given a positive integer, return its corresponding column title as appear in an Excel sheet.

For example:

1 -> A
2 -> B
3 -> C
...
26 -> Z
27 -> AA
28 -> AB 

Credits:
Special thanks to @ifanchu for adding this problem and creating all test cases

这个题被标注为Easy,事实上也的确如此,因为连官方提示都没有,但AC率只有15.8%。纳闷。

思路

一眼看去有两种思路,一是map,每个数字直接映射为对应列名,马上这个思路就导致第二个思路:进制转换。仔细一看,excel的列名不就相当于一个用字母表示的26进制计数嘛,这就简单了,只需要将10进制转换为26进制。

需要注意的是,直接转换是不行的,因为存在偏移量(offset),这是这个题目唯一的陷阱。比如1映射的是A,那0呢?1~26映射的是A-Z,无进位,但26的26进制表示是10,有进位,意味着整体向右(正方向)偏移了1位,转换的时候需要减去这个偏移量。

代码

Language:java

public class Solution {
    String b[]={"A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"};
    public String convertToTitle(int n) {
        if(n <= 0)return null;
        StringBuffer s = new StringBuffer();
        int r;
        while(n>0){
            n--;
            r=n%26;
            n=n/26;
            s.append(b[r]);
        }
        return s.reverse().toString();
    }
}
文章目录
  1. 1. 题目
  2. 2. 思路
  3. 3. 代码